package com.hedl.practice.diyJava.multithreading.wait_notify;

import com.hedl.practice.diyJava.multithreading.wait_notify.tmp.TaskQueue;

import java.util.ArrayList;

public class Client {
    public static void main(String[] args) throws InterruptedException {
        TaskQueue q = new TaskQueue();
        ArrayList<Thread> ts = new ArrayList<>();

        for (int i = 0; i < 5 ; i++){
            Thread t = new Thread(){
                public void run(){
                    //执行task:
                    while(true){
                        String s = null;
                        try {
                            s = q.getTask();
                        } catch (InterruptedException e) {
                            return;
                        }
                        System.out.println("execute task: "+s);
                    }
                }
            };
            t.start();
            ts.add(t);
        }

        Thread add = new Thread(() -> {
            for (int i = 0; i < 10; i++){
                //放入task:
                String s = "t-"+Math.random();
                System.out.println("add task: "+s);
                q.addTask(s);
                try {
                    Thread.sleep(100);      //添加之后等了100毫秒，为了给线程唤醒和取出元素预留了时间
                } catch (InterruptedException e) {
                }
            }
        });

        add.start();
        add.join();
        Thread.sleep(100);
        for (Thread t : ts) {
            t.interrupt();
        }
    }
}
